package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.*;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private TaskService taskService;
    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAudit.setCreateTime(new Date());
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);

        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public InputStream processImg(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        Long bpmnInfoId = carPackageAudit.getBpmnInfoId();
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(bpmnInfoId);
        //高亮节点集合
        List<String> highLightedActivities = new ArrayList<>();
        if(carPackageAudit.getStatus().equals(CarPackageAudit.STATUS_IN_ROGRESS)) {
            highLightedActivities = runtimeService.getActiveActivityIds(carPackageAudit.getInstanceId());
        } else {
            highLightedActivities = Collections.emptyList();
        }
        DefaultProcessDiagramGenerator defaultProcessDiagramGenerator = new DefaultProcessDiagramGenerator();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        /**
         * 第一个参数是我们流程图的节点信息
         * 第二个参数,高量集合节点信息
         * 第二个参数是高亮连线集合
         */
        InputStream inputStream = defaultProcessDiagramGenerator.generateDiagram(bpmnModel
                , highLightedActivities
                , Collections.emptyList()
                ,"宋体","宋体","宋体"
        );
        return inputStream;
    }

    @Override
    public void cancelApply(Long id) {
        //判断状态是否在审核中
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        if(!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("非法操作");
        }
        //修改状态
        carPackageAuditMapper.changeStarts(id , CarPackageAudit.STATUS_CANCEL);

        //修改服务单项状态
        serviceItemMapper.changeAuditStatus(carPackageAudit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);

        //删除流程实例
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId() , "不要了");

    }

    @Override
    public void audit(Long id, Integer auditStatus, String info) {
        //根据id查询数据
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //判断状态是否是审核中的状态
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("非法操作");
        }
        //调用activiti api去完成任务,在完成任务的时候设置流程变量
        Map<String, Object> map = new HashMap<>();
        map.put("auditStatus",auditStatus);

        //获取当前节点任务,完成任务设置流程变量
        Task currentTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        taskService.complete(currentTask.getId(),map);
        //判断是否是审核通过还是审核拒绝
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            //审批通过 TODO 审批通过
            //判断是否有下一个节点
            Task nextTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            if (nextTask != null) {
                //有下一个节点
                //拿到节点审核人 设置到carPackageAudit 当中
                carPackageAudit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
            } else {
                //没有下一节点,说明优惠后金额小于3000,就设置状态为审核通过
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);

                //修改服务单项的状态改为重新调整
                serviceItemMapper.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
            }

            //设置审核信息
            carPackageAudit
                    .setInfo(carPackageAudit.getInfo() + "<br>" + ShiroUtils.getUser().getUserName() + "审核通过 意见为:" + info);
        } else if (CarPackageAudit.STATUS_REJECT.equals(auditStatus)){
            //审批拒绝 TODO 审批拒接
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
            carPackageAudit
                    .setInfo(carPackageAudit.getInfo() + "<br/>" + ShiroUtils.getUser().getUserName() + "审批拒绝 意见为:" + info);
            //修改服务单向状态改为重新调整
            serviceItemMapper.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
        }
        //设置审核时间
        carPackageAudit.setAuditTime(new Date());
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }
}
